package cn.goktech.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.RequestWrapper;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import com.google.gson.Gson;

import cn.goktech.entity.Blog;
import cn.goktech.entity.User;
import cn.goktech.service.IBlogService;
import cn.goktech.service.IUserService;
import cn.goktech.service.impl.BlogServiceImpl;
import cn.goktech.service.impl.UserServiceImpl;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String task=request.getParameter("task");
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		IUserService userService = new UserServiceImpl();
		
		if("checkName".equals(task)){
			String username = request.getParameter("username");
			User user = userService.queryUserName(username);
			if(user!=null){
				out.write("false");
			}else{
				out.write("true");
			}
		}else if("reg".equals(task)){
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			int reg = userService.reg(user);
			if(reg>0){
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}else{
				out.println("<script>alert('注册失败');window.location.href='reg.jsp'</script>");
			}
		}else if("checkCode".equals(task)){
			String string = (String)session.getAttribute("rand");
			String code = request.getParameter("code");
			if(string.equals(code)){
				out.write("true");
			}else{
				out.write("false");
			}
		}else if("login".equals(task)){
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			
			user = userService.login(user);
			if(user!=null){
				session.setAttribute("users", username);
				session.setAttribute("username", user.getUsername());
				session.setAttribute("userId", user.getId());
				User user2=userService.queryUser(user.getId());
				session.setAttribute("userImg", user2.getImg());
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}else{
				out.println("<script>alert('登录失败');window.location.href='login.jsp'</script>");
			}
		}else if("logout".equals(task)){
			request.getSession().invalidate();
			response.sendRedirect("index.jsp");
		}else if("out".equals(task)){
		    session.removeAttribute("reqUser");  
			response.sendRedirect("index.jsp");
		}else if(task.equals("queryUserById")){
			int id=(int) session.getAttribute("userId");
			User user = userService.queryUser(id);
			request.setAttribute("user", user);
			left(request);
			request.getRequestDispatcher("user/about.jsp").forward(request, response);
		}else if(task.equals("updateUser")){
			int id = Integer.parseInt(request.getParameter("id"));
			String username = request.getParameter("username");
			String sex = request.getParameter("sex");
			String tel = request.getParameter("tel");
			User user = new User();
			user.setId(id);
			user.setUsername(username);
			user.setSex(sex);
			user.setTel(tel);
			int update = userService.updateUser(user);
			left(request);
			if(update>0){
				response.sendRedirect("user/about.jsp");
			}else{
				out.println("<script>alert('修改失败')</script>");
			}
		}else if(task.equals("updatePassword")){
			int id = Integer.parseInt(request.getParameter("id"));
			String password = request.getParameter("password");
			User user = new User();
			user.setId(id);
			user.setPassword(password);
			int update = userService.updatePassword(user);
			left(request);
			if(update>0){
				out.println("<script>alert('修改成功！请重新登录！');window.location.href='login.jsp'</script>");
			}else{
				out.println("<script>alert('修改失败')</script>");
			}
		}else if(task.equals("changePic")){
			int id=(int) session.getAttribute("userId");
			try {
				left(request);
				Map<String, String> map = parseRequest(request);
				User user = new User();
				user.setImg(map.get("img"));
				user.setUsername(map.get("name"));
				user.setId(id);
				int updata = userService.updateImg(user);
				if(updata>0){
					session.setAttribute("userImg", user.getImg());
					response.sendRedirect("user/about.jsp");
				}else{
					out.println("<script>alert('修改失败')</script>");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	private Map<String, String> parseRequest(HttpServletRequest request) throws Exception {
		
		Map<String, String> map = new HashMap<String,String>();
		
		DiskFileUpload fileUpload = new DiskFileUpload();
		
		List<FileItem> list = fileUpload.parseRequest(request);
		for (FileItem fileItem : list) {
			if(fileItem.isFormField()){
				String name=fileItem.getFieldName();
				String value = fileItem.getString("utf-8");
				map.put(name, value);
			}else{
				String name=fileItem.getFieldName();
				String oldName = fileItem.getName();
				String newName = makeNewName(oldName);
				System.out.println(newName);
				String realPath = "F:/images/"+newName;
				fileItem.write(new File(realPath));
				map.put(name, newName);
			}
		}
		
		return map;
	}

	private String makeNewName(String oldName) {
		String newName = null;
		String type = oldName.substring(oldName.lastIndexOf("."));
		
		System.out.println("type:"+type);
		
		newName = UUID.randomUUID().toString();
		
		return newName+type;
	}

	private void left(HttpServletRequest request){
		
		IBlogService blogService = new BlogServiceImpl();
		
		List<Blog> newblogList = blogService.newBlogList();
		request.setAttribute("newblogList", newblogList);
		
		List<Blog> hotblogList = blogService.hotBlogList();
		request.setAttribute("hotblogList", hotblogList);
		
		int id = Integer.parseInt(request.getParameter("id"));
		Blog blog = blogService.queryBlog(id);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
